package com.cxs.controller;

import com.cxs.dto.MenuDTO;
import com.cxs.enums.HospitalErrorResultEnum;
import com.cxs.exception.HospitalException;
import com.cxs.pojo.Menu;
import com.cxs.pojo.User;
import com.cxs.service.MenuService;
import com.cxs.service.UserService;
import com.cxs.vo.MenuTreeVO;
import com.cxs.vo.MenuVO;
import com.cxs.vo.Result;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/*
 * @Author:cxs
 * @Date:2021/10/15  19:43
 * @Version 1.0
 * @Motto:放下杂念,只为迎接明天更好的自己
 * */
@Slf4j
@RestController
@RequestMapping("/menu")
public class MenuController {
    @Autowired
    private UserService userService;
    @Autowired
    private MenuService menuService;

    /**
     * 根据用户id查询拥有菜单
     *
     * @return
     */
    @RequestMapping("/list")
    public List<MenuVO> list() {
        User user = getUser();
        if (user == null) return null;
        return userService.menuList(user.getUserId());
    }

    /**
     * 查询树形所有菜单
     *
     * @param title    条件
     * @param id       条件
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("/queryMenuAllList")
    public Result list(String title,
                       Integer id,
                       @RequestParam(value = "page", defaultValue = "1") Integer pageNo,
                       @RequestParam(value = "limit", defaultValue = "5") Integer pageSize) {
        User user = getUser();
        if (user == null) return null;
        PageInfo<Menu> menuPageInfo = menuService.menuListByPage(id, title, pageNo, pageSize);
        List<MenuVO> menuVOS = new ArrayList<>();
        menuPageInfo.getList().forEach(menu -> {
            MenuVO menuVO = new MenuVO();
            BeanUtils.copyProperties(menu, menuVO);
            if(menu.getSpread() == 1) menuVO.setSpread(true);
            menuVOS.add(menuVO);
        });
        Result result = new Result();
        result.put("count", menuPageInfo.getTotal());
        result.put("code", 0);
        result.put("msg", "");
        result.put("data", menuVOS);
        return result;
    }

    /**
     * 查询新增修改时的树形菜单
     *
     * @param spread
     * @return
     */
    @PostMapping("/loadMenuMangerLeftTreeJson")
    public Result loadMenuMangerLeftTreeJson(String spread) {
        List<MenuTreeVO> menuList = menuService.loadMenuMangerLeftTreeJson(spread);
        return Result.Ok(0, "", menuList);
    }

    /**
     * 添加菜单
     *
     * @return
     */
    @PostMapping("/addMenu")
    public Result addMenu(@Valid MenuDTO menuDTO, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            log.error("【菜单模块】：父菜单的id不能为空,menu = {}", menuDTO);
            throw new HospitalException(HospitalErrorResultEnum.MENU_PARAMETER_ERROR);
        }
        Menu menu = new Menu();
        BeanUtils.copyProperties(menuDTO, menu);

        menuService.insert(menu);

        return Result.Ok("菜单添加成功");
    }

    @PostMapping("/updateMenu")
    public Result updateMenu(@Valid MenuDTO menuDTO, BindingResult bindingResult) {
        if (StringUtils.isEmpty(menuDTO.getId())) {
            log.error("【菜单模块】：菜单的id不能为空,menu = {}", menuDTO);
            throw new HospitalException(HospitalErrorResultEnum.MENU_PARAMETER_ERROR);
        }
        if (bindingResult.hasErrors()) {
            log.error("【菜单模块】：参数传递错误,menu = {}", menuDTO);
            throw new HospitalException(HospitalErrorResultEnum.MENU_PARAMETER_ERROR.getCode(), bindingResult.getFieldError().getDefaultMessage());
        }
        Menu menu = new Menu();
        BeanUtils.copyProperties(menuDTO, menu);

        menuService.update(menu);

        return Result.Ok("菜单修改成功");
    }

    /**
     * 判断菜单是否有孩子
     * @param id
     * @return
     */
    @PostMapping("/checkMenuHasChildren")
    public Result checkMenuHasChildren(Integer id){
        if (StringUtils.isEmpty(id)) {
            log.error("【菜单模块】：菜单的id不能为空,id = {}", id);
            throw new HospitalException(HospitalErrorResultEnum.MENU_PARAMETER_ERROR);
        }
        Integer count = menuService.checkMenuHasChildren(id);

        return Result.Ok(count);
    }

    /**
     * 删除菜单
     * @param id
     * @return
     */
    @PostMapping("/deleteMenu")
    public Result deleteMenu(Integer id){
        if (StringUtils.isEmpty(id)) {
            log.error("【菜单模块】：菜单的id不能为空,id = {}", id);
            throw new HospitalException(HospitalErrorResultEnum.MENU_PARAMETER_ERROR);
        }
        menuService.delete(id);

        return Result.Ok("删除成功");
    }


    private User getUser() {
        Subject subject = SecurityUtils.getSubject();

        Object principal = subject.getPrincipal();

        if (principal != null) {
            return (User) principal;
        }
        return null;
    }
}
